# coding=utf-8
__author__ = 'liubin'

import math


def query_paging(query, size, start):
    """
    分页处理
    :param query:查询结果
    :param size:每页大小
    :param page:当前页数
    :return:
    """
    #print(size, start)
    total = query.count()
    page = None
    if size is not None and start is not None:
        size = int(size)
        start = int(start)
        length = int(math.ceil(float(total)/size))
        page = int(math.ceil(float(start+1)/size))
        start = (page-1)*size
        if start < 0:
            start = 0
            page = 1
        elif start >= total:
            page = length
            start = (page-1)*size
        end = page*size
        if end < 1:
            end = 1
        elif end > total:
            end = total
        query = query.slice(start, end)
    return {
        'query': query,
        'total': total,
        'page': page if page is not None else 1,
        'start': start
    }

def get_form_error(form):
    """
    返回wtforms的error
    :param form: 处理用的form
    :return:返回值
    """
    messages = []
    for error in form.errors:
        label = form.__getitem__(error).label.text
        for msg in form.errors[error]:
            messages.append(label + ':' + msg)
    return messages